<?php

if (!function_exists('memory_get_usage')) {
	function memory_get_usage()
	{
		$pid = getmypid();
		exec("ps -o rss -p $pid", $output);
		return $output[1] *1024;	
	}
}

function error($msg, $level=NULL)
{
	global $___debug_sid;
	global $_FU_START_TIME;
	global $___checkpoint_time;
	$time = microtime(true);
	global $___checkpoint_mem;
	$mem = memory_get_usage();
	error_log(
		'['.sprintf( '%d %.4f %.4f - %.4f %.4f', 
		$___debug_sid ,
		$time-$___checkpoint_time,
		($mem-$___checkpoint_mem)/1048576,
		$time-$_FU_START_TIME,
		$mem/1048576
	)
	.'] ! '
	.preg_replace('#\\n\\s*#s', ' ', $msg), 0);
}

function debug($msg, $level=NULL)
{
	global $___debug_sid;
	global $_FU_START_TIME;
	global $___checkpoint_time;
	$time = microtime(true);
	global $___checkpoint_mem;
	$mem = memory_get_usage();
	error_log(
		'['.sprintf( '%d %.4f %.4f - %.4f %.4f', 
		$___debug_sid ,
		$time-$___checkpoint_time,
		($mem-$___checkpoint_mem)/1048576,
		$time-$_FU_START_TIME,
		$mem/1048576
	)
	.'] . '
	.preg_replace('#\\n\\s*#s', ' ', $msg), 0);
}

function trace($msg, $level=NULL)
{
	global $___debug_sid;
	global $_FU_START_TIME;
	global $___checkpoint_time;
	$time = microtime(true);
	global $___checkpoint_mem;
	$mem = memory_get_usage();
	error_log(
		'['.sprintf( '%d %.4f %.4f - %.4f %.4f', 
		$___debug_sid ,
		$time-$___checkpoint_time,
		($mem-$___checkpoint_mem)/1048576,
		$time-$_FU_START_TIME,
		$mem/1048576
	)
	.'] . '.$msg, 0);
}

function checkpoint($facility, $msg, $level=NULL)
{
	global $___debug_sid;
	global $_FU_START_TIME;
	global $___checkpoint_time;
	$time = microtime(true);
	global $___checkpoint_mem;
	$mem = memory_get_usage();
	error_log(
		'['.sprintf( '%d %.4f %.4f - %.4f %.4f', 
		$___debug_sid ,
		$time-$___checkpoint_time,
		($mem-$___checkpoint_mem)/1048576,
		$time-$_FU_START_TIME,
		$mem/1048576
	)
	.'] --- '.$facility
	.' '.$msg, 0);
	$___checkpoint_time = $time;
	$___checkpoint_mem = $mem;
}

// используем в качестве id процесса для вывода сообщений
// (полезно для разгребания логов, когда льется все вперемешку)
global $___debug_sid;
global $___checkpoint_time;
global $___checkpoint_mem;
global $_FU_START_TIME;
$___debug_sid = rand(10, 99);
$___checkpoint_time = isset($_FU_START_TIME) ? $_FU_START_TIME : microtime(true);
$___checkpoint_mem = isset($_FU_START_MEM) ? $_FU_START_MEM : memory_get_usage();

